import path from './path.js'
import cache from './token.js'
export function CommonUpload() {
	return new Promise((resolve, rej) => {
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册选择，和摄像头功能，默认二者都有
			crop: {
				width: 610,
				height: 610
			},
			success: res => {
				uni.uploadFile({
					url: path.imgApi + '/upload_img',
					data: 'POST',
					filePath: res.tempFilePaths[0],
					fileType: 'image/',
					name: 'file',
					method: 'post',
					header: {
						'Content-Type': 'application/json;charset=UTF-8',
						'Authorization': 'bearer ' + cache.getCache('youthToken')
					},
					success: (res) => {
						uni.hideLoading();
						let hasRes = JSON.parse(res.data);
						if (hasRes.status_code == 200) {
							resolve(path.baseUrl + hasRes.data.data);
						} else {
							uni.showToast({
								title: hasRes.message,
								icon: 'none'
							})
						}
					},
					fail: (error) => {
						console.log('上传失败了', error)
					}

				})
			},
			fail: res => {
				console.log('上传失败', res)
			}
		});
	})
}

export function CommonUploadFiles() {
	return new Promise((resolve, rej) => {
		uni.chooseMessageFile({
			count: 1, // 一次只能选择一个文件
			type: 'file', // 选择文件
			extension: ['pdf','PDF'], // 限定文件类型为PDF
			success: (res) => {
				let fileName = res.tempFiles[0].name
				uni.showLoading({
					title: '正在上传,请稍后'
				});
				// 获取到文件路径                
				uni.uploadFile({
					url: path.imgApi + '/upload_file',
					data: 'POST',
					filePath: res.tempFiles[0].path,
					// fileType: 'image',
					name: 'file',
					method: 'post',
					header: {
						'Content-Type': 'application/json;charset=UTF-8',
						'Authorization': 'bearer ' + cache.getCache('youthToken')
					},
					success: (res) => {
						uni.hideLoading();
						let hasRes = JSON.parse(res.data);
						if (hasRes.status_code == 200) {
							resolve({
								fileName: fileName,
								fileUrl: path.baseUrl + hasRes.data.data
							});
						} else {
							uni.showToast({
								title: hasRes.message,
								icon: 'none'
							})
						}
					},
					fail: (error) => {
						console.log('上传失败了', error)
					}

				})
			},
			fail: (err) => {
				console.error('选择文件失败：', err);
			}
		});
	})
}